package com.cy.service;

import com.cy.config.Config;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * @Author jiangwang
 * @Created by 2021/12/16 9:12
 * @Description: TODO
 */
@Component
public class StartRunner implements CommandLineRunner
{

    private static final Logger logger = LoggerFactory.getLogger(StartRunner.class);

    @Value("${webserviceUrl}")
    private String webserviceUrl;

    @Value("${nameSpaceUrl}")
    private String nameSpaceUrl;

    @Override
    public void run(String... args) throws Exception
    {
        logger.info("StartupRunner...");
        //加载配置文件
        Config.webserviceUrl = webserviceUrl;
        Config.nameSpaceUrl = nameSpaceUrl;
        getMap();
        logger.info("配置文件加载结束...");
    }


    /**
     * 读取配置文件config.xml中的数据
     */
    private static void getMap()
    {
        //获取文档对象
        SAXReader reader = new SAXReader();
        Document doc = null;
        try
        {
            doc = reader.read(new File("config.xml"));
//            InputStream stream = StartRunner.class.getClassLoader().getResourceAsStream("config.xml");
//            BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
//            doc = reader.read(br);
            //获取根元素
            Element root = doc.getRootElement();
            //获取所有的子元素cy
            List<Element> users = root.elements("cy");
            //遍历cy节点下的子节点 将子节点的值添加到map集合中去
            for (Element element : users)
            {
                //设备编号
                String devNo = element.elementTextTrim("devNo");
                //卡口编号
                String kkbh = element.elementTextTrim("KKBH");
                //卡口秘钥
                String kkmy = element.elementTextTrim("KKMY");
                Config.devList.add(devNo);
                Config.kkbHMap.put(devNo, kkbh);
                Config.kkmYMap.put(devNo, kkmy);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
